﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Threading;
using Microsoft.SqlServer.Management.Trace;
using Microsoft.SqlServer.Management.Common;
using System.Threading;




namespace StressServer.Model
{
    public class QueryEndEvent
    {
        public int CPUTime;
        public int ClientProcessId;
        public int ConnectionId;
        public DateTime CurrentTime;
        public DateTime StartTime;
        public DateTime EndTime;
        public string DatabaseName;
        public int Duration;
        public int Error;
        public int SPID;
        public int RequestID;
        public Guid SessionID;
        public string TextData;
    }

    public class ProfilerReader
    {
        #region Event declarations
        public delegate void QueryEndEventRecieved();
        public event QueryEndEventRecieved OnEventRecieved;
        #endregion

        #region Members
        public ObservableCollection<QueryEndEvent> QueryEndEvents;
        private TraceServer _Server;
        private SqlConnectionInfo _Connection;
        private DispatcherTimer _Timer;
        private bool _StopTrace = false;

        public bool StopTrace
        {
            get { return _StopTrace; }
            set { _StopTrace = value; }
        }
        #endregion
        public ProfilerReader(string Server)
        {
            _Server = new TraceServer();
            _Connection = new SqlConnectionInfo(Server);
            QueryEndEvents = new ObservableCollection<QueryEndEvent>();

        }

        public void StartTrace()
        {
            _Connection.UseIntegratedSecurity = true;
            _Server.InitializeAsReader(_Connection, Environment.CurrentDirectory + "//SSAS 2012.tdf");
            _Timer = new DispatcherTimer();
            _Timer.Interval = TimeSpan.FromSeconds(1);
            _Timer.Tick += _Timer_Tick;
            _Timer.Start();
        }

        void _Timer_Tick(object sender, EventArgs e)
        {
            _Timer.Stop();
            if (!StopTrace)
            {
                ReadTrace();
                
            }
            else
            {
                _Server.Stop();
                _Server.Close();
                _Timer.Stop();

            }
        }

        public void ReadTrace()
        {
            for (int i = 0;i<_Server.FieldCount;i++) 
            {
                Console.WriteLine(_Server.GetName(i));
            }
            while (_Server.Read())
            {
                var EventId = _Server["LoginName"];
                //var t = _Server["Event Class"];
                QueryEndEvent ThisEvent = new QueryEndEvent();
            }
            _Timer.Start();
        }
    }
}
